package com.ledim.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.View;
import com.ledim.activity.Card9ListActivity;
import com.ledim.activity.LedimChannelsActivity;
import com.ledim.activity.LedimTagsActivity;
import com.ledim.activity.UserLoginActivity;
import com.ledim.activity.base.LedimWebViewActivity;
import com.ledim.app.LeDimApplication;
import com.ledim.bean.LedimChoiceCardBean;
import com.ledim.bean.LedimPushBean;
import com.ledim.datastatistics.LeDimAnalysisUtils;
import com.ledim.fragment.CommonDialogFragment;
import com.ledim.itf.LedimDialogClickListner;
import com.letv.android.client.LetvSDK;
import com.letv.android.client.activity.AlbumPlayActivity;
import com.letv.android.client.activity.AlbumPlayRoomActivity;
import com.letv.android.young.client.R;
import com.letv.core.bean.IVideo;
import com.letv.core.constant.PlayConstant;
import com.letv.tracker2.enums.EventType;
import com.letv.tracker2.enums.Key;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;


/**
 * Created by ccx on 16/8/18.
 * 乐次元业务相关common逻辑
 */
public class LedimFunctionUtils {

    public static String FILEPATH = Environment.getExternalStorageDirectory() + "/.LETV/.cache/";
    private static TypedArray tagColos;

    /**
     * @param activity
     *         弹登录提示框
     */
    public static void showLoginDialog(final FragmentActivity activity) {
        String hint = "该功能需要登录,\n大王穿上马甲再继续吧？";
        CommonDialogFragment dialogFragment =
                CommonDialogFragment.getInstance(ConstantUtil.DialogConstant.DIALOG_HORIZONTAL_TYPE, hint, "登录", "取消", new LedimDialogClickListner() {
                    @Override
                    public void onClickPositive(View view) {
                        Intent intent = new Intent(activity, UserLoginActivity.class);
                        activity.startActivity(intent);
                    }

                    @Override
                    public void onClickNegative(View view) {

                    }

                    @Override
                    public void onDismiss() {

                    }
                });
        dialogFragment.showDialog(activity.getSupportFragmentManager());
    }

    /**
     * @param activity
     *         弹登录提示框
     */
    public static void showLoginDialog(final FragmentActivity activity,
                                       final LedimDialogClickListner listener) {

        String hint = "该功能需要登录,\n大王穿上马甲再继续吧？";
        CommonDialogFragment dialogFragment =
                CommonDialogFragment.getInstance(ConstantUtil.DialogConstant.DIALOG_HORIZONTAL_TYPE, hint, "登录", "取消", listener);
        dialogFragment.showDialog(activity.getSupportFragmentManager());
    }

    /**
     * @param status
     * @return 通过status字段获取用户身份图标
     */
    public static int getUserTypeIcon(String status) {
        //判断身份
        if (status.equals("1")) {
            //大神
            return R.drawable.user_level_biggod;

        } else if (status.equals("2")) {
            //官方
            return R.drawable.user_level_authority;
        }
        //普通用户 status.equals("0") 和 默认
        return R.drawable.profile_user_level_normal;
    }

    public static String getImageName() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_HHmmss");
        Date date = new Date();
        String time = format.format(date);
        String imageName = "IMG_" + time + ".jpg";
        return imageName;
    }

    public static String formatRating(String rating) {
        BigDecimal num = new BigDecimal(rating);
        DecimalFormat fmt = new DecimalFormat("#############0.0");
        return fmt.format(num);
    }

    public static String formatGoldCount(long count) {
        if (count < 10000) {
            return count + "";
        } else if (count < 100000000) {
            float c = (float) count / 10000.0f;
            return formatRating(c + "") + "万";
        } else {
            float c = (float) count / 100000000.0f;
            return formatRating(c + "") + "亿";
        }
    }

    /**
     * @param mActivity
     * @param card
     * @param cardId
     *         处理首页card卡片跳转逻辑 并做大数据事件统计
     */
    public static void jumpTargetActivity(Activity mActivity, LedimChoiceCardBean card,
                                          String cardId) {
        if (card == null) {
            return;
        }
        HashMap<String, String> params = new HashMap<String, String>();
        params.put(Key.Type.name(), "homepageCard");
        params.put("fragId", cardId);
        if (card.simple_album != null && !TextUtils.isEmpty(card.simple_album.album_id)) {
            params.put("albumId", card.simple_album.album_id);
        }
        if (card.room != null && !TextUtils.isEmpty(card.room.roomId)) {
            params.put("roomId", card.room.roomId);
        }
        Intent intent = null;
        switch (card.type) {
            case ConstantUtil.CardType.album:
            case ConstantUtil.CardType.video:
                IVideo video = new IVideo();
                video.setmVid(0);
                LetvSDK.getInstance().play(mActivity, video, false, card);
                break;

            case ConstantUtil.CardType.room:
                if (card.room != null) {
                    if (card.room.roomId != null) {
                        IVideo roomVideo = new IVideo();
                        roomVideo.setmVid(0);
                        if (card.room.user.userId.equals(LedimSpUtils.getUid())) {
                            LetvSDK.getInstance()
                                   .playRoom(mActivity, roomVideo, card.room, true, false);
                        } else {
                            LetvSDK.getInstance().playRoom(mActivity, roomVideo, card.room);
                        }
                    }
                }
                break;

            case ConstantUtil.CardType.channel:
                intent = new Intent(mActivity, LedimChannelsActivity.class);
                intent.putExtra(LedimChannelsActivity.CARDID, card);
                mActivity.startActivity(intent);
                params.put("tagName", card.title);
                mActivity.overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
                break;

            case ConstantUtil.CardType.star:
                IVideo roomVideo = new IVideo();
                roomVideo.setmVid(0);
                LetvSDK.getInstance().playRoom(mActivity, roomVideo, card.room);
                break;

            case ConstantUtil.CardType.banner:
                gotoWebView(card.url, card.title, mActivity);
                break;

            case ConstantUtil.CardType.tag:
                //card.media 传递media过去
                intent = new Intent(mActivity, LedimTagsActivity.class);
                intent.putExtra(ConstantUtil.ID, card.media);
                mActivity.startActivity(intent);
                break;

        }
        if (!TextUtils.isEmpty(cardId)) {
            LeDimAnalysisUtils.reportEvent(LeDimAnalysisUtils.CHOICE_PAGE_CODE, EventType.Click, params);
        }
    }

    public static int homeRandom() {
        Random rd = new Random();
        return 1 + rd.nextInt(20);
    }

    public static Drawable getRandomIcon(Context context) {
        Resources resources = context.getResources();
        Drawable drawable;
        switch (homeRandom() % 5) {
            case 0:
                drawable = resources.getDrawable(R.drawable.card_icon01);
                break;
            case 1:
                drawable = resources.getDrawable(R.drawable.card_icon02);
                break;
            case 2:
                drawable = resources.getDrawable(R.drawable.card_icon03);
                break;
            case 3:
                drawable = resources.getDrawable(R.drawable.card_icon04);
                break;
            case 4:
                drawable = resources.getDrawable(R.drawable.card_icon05);
                break;
            default:
                drawable = resources.getDrawable(R.drawable.card_icon01);
                break;
        }
        int size = DensityUtil.dip2px(context, 24);
        drawable.setBounds(0, 0, size, size);
        return drawable;
    }

    public static int getRandomColor(Context context) {
        if (tagColos == null) {
            tagColos = context.getResources().obtainTypedArray(R.array.mainhome_tag_colors);
        }
        Random rd = new Random();
        return tagColos.getColor(rd.nextInt(20) % tagColos.length(), R.color.color_B4D9FF);
    }

    /**
     * 上报搜索页面item点击事件
     */
    public static void reportSearchItemEvent(String widgetId, LedimChoiceCardBean card) {
        HashMap<String, String> params = new HashMap<String, String>();

        if (card != null && !TextUtils.isEmpty(card.link)) {
            String url = card.link.replaceAll("app://medias/", "");
            String mMediaId = url.substring(0, url.indexOf("/"));
            String mSubMediaId =
                    card.link.substring(card.link.lastIndexOf("/") + 1, card.link.length());
            if (card.type == 2 && !TextUtils.isEmpty(mMediaId)) {
                params.put("albumId", mMediaId);

            } else if (card.type == 1 && !TextUtils.isEmpty(mSubMediaId)) {
                params.put("videoid", mSubMediaId);
            }
        }
        LeDimAnalysisUtils.reportEvent(widgetId, EventType.Click, params);
    }

    /**
     * @param uid
     * @param str
     * @return 获取用户名字
     */
    public static String getUserNameColorString(String uid, String str) {
        switch (Integer.valueOf(uid) % 3) {
            case 0:
                return "<font color='#D271D4'>" + str + "</font>";
            case 1:
                return "<font color='#48B1D9'>" + str + "</font>";
            case 2:
                return "<font color='#648FEA'>" + str + "</font>";
            default:
                return "<font color='#D271D4'>" + str + "</font>";
        }
    }

    /**
     * @param url
     * @param context
     */
    public static void gotoWebView(String url, String title, Context context) {
        Intent intent = new Intent(context, LedimWebViewActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString(ConstantUtil.URL, url);
        bundle.putString(ConstantUtil.TITLE, title);
        intent.putExtra(LedimWebViewActivity.PARAM_INTENT, bundle);
        context.startActivity(intent);
    }

    /**
     * @param bean
     * @param activity
     * @return 获取push message的跳转intent
     */
    public static Intent getPushMsgIntent(LedimPushBean bean, Activity activity) {
        Intent intent = null;
        switch (bean.type) {
            case ConstantUtil.IPUSHMSGTYPE.card_msg:
                if (bean.card != null) {
                    intent = new Intent(activity != null ? activity : LeDimApplication.getInstance()
                                                                                      .getApplicationContext(), AlbumPlayActivity.class);
                    intent.putExtra(PlayConstant.CARD, bean.card);
                    intent.putExtra(PlayConstant.LAUNCH_MODE, PlayConstant.LAUNCH_MODE_ALBUM);
                }
                break;
            case ConstantUtil.IPUSHMSGTYPE.room_msg:
                if (bean.room != null) {
                    intent = new Intent(activity != null ? activity : LeDimApplication.getInstance()
                                                                                      .getApplicationContext(), AlbumPlayRoomActivity.class);
                    intent.putExtra(PlayConstant.ROOM, bean.room);
                    intent.putExtra(PlayConstant.LAUNCH_MODE, PlayConstant.LAUNCH_MODE_ALBUM);
                    intent.putExtra(PlayConstant.IS_ME,
                            bean.room.user != null && !TextUtils.isEmpty(bean.room.user.userId) &&
                                    LedimSpUtils.getUid().equals(bean.room.user.userId));
                }
                break;
            case ConstantUtil.IPUSHMSGTYPE.h5_msg:
                if (!TextUtils.isEmpty(bean.url)) {
                    intent = new Intent(activity != null ? activity : LeDimApplication.getInstance()
                                                                                      .getApplicationContext(), LedimWebViewActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString(ConstantUtil.URL, bean.url);
                    bundle.putString(ConstantUtil.TITLE, bean.title);
                    intent.putExtra(LedimWebViewActivity.PARAM_INTENT, bundle);

                }
                break;

            case ConstantUtil.IPUSHMSGTYPE.theme_msg:
                if (bean.theme != null) {
                    intent = new Intent(activity != null ? activity : LeDimApplication.getInstance()
                                                                                      .getApplicationContext(), Card9ListActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString(ConstantUtil.ID, bean.theme.id);
                    bundle.putString(ConstantUtil.PHOTO, bean.theme.photo);
                    bundle.putString(ConstantUtil.DES, bean.theme.intro);
                    bundle.putString(ConstantUtil.TITLE, bean.theme.title);
                    intent.putExtras(bundle);
                }
                break;

        }
        return intent;
    }
}
